using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Spike_EBC_Designer.ViewModel
{
    [Serializable]
    public class Relation : ModelElement
    {
        public Cell From, To;

        public string OutputPinName = "";
        public string InputPinName = "";
        public string Typename = "()";

        public bool IsSelected;


        public Relation(Cell @from, Cell to)
        {
            From = from;
            To = to;
            Resize();
        }


        internal void Resize()
        {
            var left = From;
            var right = To;

            var dX = right.X - left.X;
            var dY = right.Y - left.Y;

            base.X = left.X + left.Width/2 + Math.Sign(dX) * 10;
            base.Y = left.Y + left.Height/2 + Math.Sign(dY) * 10;
            base.Width = right.X - left.X - 2*(Math.Sign(dX) * 10);
            base.Height = right.Y - left.Y - 2*(Math.Sign(dY) * 10);
        }


        public override bool IntersectsWith(int x, int y)
        {
            var left = base.X; if (base.Width < 0) left = base.X + base.Width;
            var top = base.Y;  if (base.Height < 0) top = base.Y + base.Height;

            if (left <= x && x <= (left+Math.Abs(base.Width)) &&
                top <= y && y <= (top+Math.Abs(base.Height)))
            {
                // punkt liegt im rechteck der relation...

                // geradengleichung: y = mx + c
                // bestimmung von m
                var m = (double)base.Height/base.Width;
                // bestimmung von c
                var c = base.Y - (m*base.X);

                // ...liegt er aber auch auf der geraden?
                var fx = m*x + c;
                return (fx-5) <= y && y <= (fx+5);
            }

            return false;
        }
    }
}